import sensor, image, time
from pyb import UART
import json
ball_threshold = (46, 100, 10, 70, -17, 27)
rectangle_threshold = (31, 100, -17, 22, -30, 46)
ball_area_threshold=80
rectangle_area_threshold=50000
rect_f = 0

sensor.reset() # Initialize the camera sensor.
sensor.set_pixformat(sensor.RGB565) # use RGB565.
sensor.set_framesize(sensor.QQVGA) # use QQVGA for speed.
sensor.skip_frames(10) # Let new settings take affect.
sensor.set_auto_whitebal(False) # turn this off.
clock = time.clock() # Tracks FPS.

uart = UART(3, 115200)

def find_max(blobs):
    max_size=0
    for blob in blobs:
        if blob.pixels() > max_size:
            max_blob=blob
            max_size = blob.pixels()
    return max_blob

while(True):
    clock.tick()
    img = sensor.snapshot()#.lens_corr(1.8) #拍摄一张照片，lens_corr函数用于非鱼眼畸变矫正
    rects = img.find_blobs([rectangle_threshold])
    if rects:
        max_rect = find_max(rects)
        rect_f = 1
    else:
        print("no widget")
    balls = img.find_blobs([ball_threshold])
    if balls:
        max_ball = find_max(balls)
        img.draw_rectangle(max_ball.rect())
        if rect_f:
            X = int(max_ball.cx()-max_rect.cx())
            Y = int(max_ball.cy()-max_rect.cy())
            output_str = "[%d,%d]" % (X,Y)
            print(output_str)
            img.draw_rectangle(max_rect.rect())
            uart.write(output_str)
    #print(clock.fps())
